/* ---------------------------------------------------购物车------------------------------------------------------------- */
import { useState, useEffect } from 'react';
import Title from '../components/title.jsx';
/* 引入css */
import '../assent/less/cart.css';
/* 引入react-vant */
import { ProductCard, Stepper, Cell, Space, Checkbox, SubmitBar, Toast, Dialog, Empty } from 'react-vant';
import { DeleteO } from '@react-vant/icons';
// 引入axios
import { cartlist, cartdelete } from "../request/app.js";

import { Link } from 'react-router-dom'
function Cart() {

  let [title, setTitle] = useState('购物车');
  let [active, setActive] = useState(0); // 导航栏状态
  let [cartlistCart, setcartlistCart] = useState([]); // 购物车商品列表
  let [cartlistTen, setcartlistTen] = useState([]);  // 万人团商品列表
  let [listLenth, setlistLenth] = useState(""); // 商品总数
  let [checkedAll, setcheckedAll] = useState(false); // 全选状态
  let [totalPrices, settotalPrices] = useState(0);     // 总价

  useEffect(() => {
    // 获取购物车数据
    cartlist({
      uid: localStorage.getItem('userinfo') ? JSON.parse(localStorage.getItem('userinfo')).uid : undefined
    }).then(res => {
      /* 商品总数 */
      let num = 0;
      let num1 = 0;
      if (res.list[0].content != null) {
        num = res.list[0].content.length;
        res.list[0].content.forEach(item => {
          return item.checked = false;
        })
      }
      if (res.list[1].content != null) {
        num1 = res.list[1].content.length;
        res.list[1].content.forEach(item => {
          return item.checked = false;
        })
      }
      cartlistTen = res.list[0].content ? res.list[0].content : []; // 万人团
      cartlistCart = res.list[1].content ? res.list[1].content : [];  // 购物车
      listLenth = num + num1;  // 总商品数量

      setcartlistCart([
        ...cartlistCart
      ]);
      setcartlistTen([
        ...cartlistTen
      ]);
      setlistLenth(listLenth);

    })

  }, [])

  /* 万人团商品 */
  let cart_1 = null;
  if (cartlistTen.length == 0) {
    cart_1 = ''

  } else {
    cart_1 = <div className='top'>
      {/* 标题 */}
      <div className='title'>
        <h3>万人团</h3>
        <div>
          <span>以免运费</span>|<span className='giftCoupon'>领券</span>
        </div>
      </div>
      <div className='cart'>
        {cartlistTen.map((item, index) => {

          return (
            <ProductCard
              key={item.id}
              num={item.num}
              price={item.price}
              title={item.goodsname}
              thumb={item.img}
              tags={

                <Checkbox checked={item.checked} onClick={() => cartC(index, item.id)}></Checkbox>

              }
              tag={

                <Space className='demo-icon' gap={20}>
                  {/* 删除 */}
                  <DeleteO onClick={() => del(item.id, index)} />
                </Space>
              }
              footer={
                <Cell title="" center>
                  <Stepper
                    min={0}
                    max={99}
                  // onPlus={() => this.onPlus()}
                  // onMinus={() => this.onMinus()}
                  />
                </Cell>
              }
            />

          )

        })}

      </div>
    </div>
  }
  /* 购物车商品 */
  let cart_2 = null;
  if (cartlistCart.length == 0) {
    cart_2 = ""
  } else {
    cart_2 = <div className='bottom'>
      {/* 标题 */}
      <div className='title'>
        <h3>小U自营</h3>
        <div>
          <span>以免运费</span>|<span className='giftCoupon'>领券</span>
        </div>
      </div>
      <div className='cart'>
        {
          cartlistCart.map((item, index) => {
            return (
              <ProductCard
                key={item.id}
                num={item.num}
                price={item.price}
                title={item.goodsname}
                thumb={item.img}
                tags={

                  <Checkbox checked={item.checked} onClick={() => cartC(index, item.id)}></Checkbox>

                }
                tag={

                  <Space className='demo-icon' gap={20}>
                    {/* 删除 */}
                    <DeleteO onClick={() => del(item.id, index)} />
                  </Space>
                }
                footer={
                  <Cell title="" center>
                    <Stepper
                      min={0}
                      max={99}
                    // onPlus={() => this.onPlus()}
                    // onMinus={() => this.onMinus()}
                    />
                  </Cell>
                }
              />
            )
          })
        }

      </div>
    </div>
  }

  /* 购物车主体内容 */  /* 购物车为空显示空状态 */
  let cartMain = null;
  if (cartlistTen.length == 0 && cartlistCart.length == 0) {
    cartMain = <Empty
      className="custom-image"
      imageSize={200}
      image={<img src="https://img.yzcdn.cn/vant/custom-empty-image.png" />}
      description="快去添加商品吧!"
    />
  } else {
    cartMain = <main>
      {/* 万人团商品 */}
      {cart_1}
      {/* 购物车商品 */}
      {cart_2}
    </main>
  }
  /* 删除 */
  function del(Cartid, index) {

    Dialog.confirm({
      message: '确认要删除商品吗?',
    })
      .then(() => {
        cartdelete({
          id: Cartid
        }).then(res => {

          if (cartlistCart[index].id == Cartid) {
            /* 删除对应的数组(购物车数据) */
            cartlistCart.splice(index, 1)
            setcartlistCart([
              ...cartlistCart
            ])
            setcartlistTen([
              ...cartlistTen
            ])
            setlistLenth(listLenth)
            /* 计算总价 */
            let price = 0;
            cartlistCart.forEach(item => {
              if (item.checked == true) {
                price += item.price * item.num
              }
              return price
            })
            cartlistTen.forEach(item => {
              if (item.checked == true) {
                price += item.price * item.num
              }
              return price
            })
            totalPrices = price;
            settotalPrices(totalPrices);
            Toast.success('删除成功');
            return
          }
          if (cartlistTen[index].id == Cartid) {
            /* 删除对应的数组(万人团数据) */
            cartlistTen.splice(index, 1)
            setcartlistCart([
              ...cartlistCart
            ])
            setcartlistTen([
              ...cartlistTen
            ])
            setlistLenth(listLenth)
            /* 计算总价 */
            let price = 0;
            cartlistCart.forEach(item => {
              if (item.checked == true) {
                price += item.price * item.num
              }
              return price
            })
            cartlistTen.forEach(item => {
              if (item.checked == true) {
                price += item.price * item.num
              }
              return price
            })
            totalPrices = price;
            settotalPrices(totalPrices);
            Toast.success('删除成功');
            return
          }

        })
      })
      .catch(() => { })
  }
  /* 全选 */
  function onChangeAll() {

    checkedAll = !checkedAll;
    setcheckedAll(checkedAll);
    /* 计算总价 */
    let price = 0;
    cartlistCart.forEach(item => {
      item.checked = checkedAll
      if (item.checked == true) {
        price += item.price * item.num
      }
    });

    cartlistTen.forEach(item => {
      item.checked = checkedAll
      if (item.checked == true) {
        price += item.price * item.num
      }
    });

    totalPrices = price;

    settotalPrices(totalPrices);
    setcartlistCart([
      ...cartlistCart
    ]);
    setcartlistTen([
      ...cartlistTen
    ]);
  }
  /* 单选 */
  function cartC(index, cartId) {
    if (cartlistCart[index].id == cartId) {
      cartlistCart[index].checked = !cartlistCart[index].checked;
    }
    if (cartlistTen[index].id == cartId) {
      cartlistTen[index].checked = !cartlistTen[index].checked;
    };
    let a = cartlistCart.every(item => {
      return item.checked
    });
    let b = cartlistTen.every(item => {
      return item.checked
    });
    if (a == true && b == true) {
      checkedAll = true;
    } else {
      checkedAll = false;
    };
    setcartlistCart([
      ...cartlistCart
    ]);
    setcartlistTen([
      ...cartlistTen
    ]);
    setcheckedAll(checkedAll);
    /* 计算总价 */
    let price = 0;
    cartlistCart.forEach(item => {
      if (item.checked == true) {
        price += item.price * item.num
      }
      return price
    })
    cartlistTen.forEach(item => {
      if (item.checked == true) {
        price += item.price * item.num
      }
      return price
    })
    totalPrices = price;
    settotalPrices(totalPrices);
  }


  /* 是否登录 */
  let info = ''
  if (localStorage.getItem('userinfo')) {
    info = [cartMain]
  } else {

    info = <Link to='/login' style={{
      fontSize: "0.24rem",
      color: '#000',
    }}>还没登陆，去登陆</Link>
  }
  return (
    <div id='cart'>
      {/* 头部 */}
      <header>
        {/* 标题 */}
        <Title title={title}></Title>
        {/* 导航栏 */}
        <ul>
          <li className={active == 0 ? 'active' : ''} onClick={() => {
            setActive(0)
          }}>
            <span>全部({listLenth})</span>
            <i></i>
          </li>
          <li className={active == 1 ? 'active' : ''} onClick={() => {
            setActive(1)
          }}>
            <span>降价(0)</span>
            <i></i>
          </li>
          <li className={active == 2 ? 'active' : ''} onClick={() => {
            setActive(2)
          }}>
            <span>常卖(0)</span>
            <i></i>
          </li>
          <li className={active == 3 ? 'active' : ''} onClick={() => {
            setActive(3)
          }}>
            <span>分类(0)</span>
            <i></i>
          </li>
        </ul>
      </header>

      {/* 购物车主体 */}
      {info}

      {/* 底部 */}
      <footer>
        <div className="demo-submit-bar">
          <SubmitBar
            price={totalPrices * 100}
            buttonText="去结算"
          // onSubmit={() => this.Submit()}
          >
            <Checkbox checked={checkedAll} onChange={() => onChangeAll()}>全选</Checkbox>

          </SubmitBar>
        </div>
      </footer>
    </div>
  );

}

export default Cart;